<template>
  <div class="popup_class" :id="id">
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill  flex-1"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  :style="{height: (gadgetHeight + heightoffset -10) + 'px'}">
        <el-card v-loading="loading"
                 shadow="never"
                 class="aui-card--fill  flex-1"
                 :style="{height: (gadgetHeight + heightoffset -10) + 'px'}">
          <div>
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(gadgetSetting.headerTitle && gadgetSetting.headerTitle.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <span>
                <span class="cardTitle threepoints"
                      :title="gadgetSetting.headerTitle"
                      v-if='gadgetSetting.headerTitle && gadgetSetting.headerTitle.trim().length>0'>{{ gadgetSetting.headerTitle }}</span>
                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="gadgetSetting.headerDescription"
                            placement="right"
                            v-if='gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0'>
                  <i class="cuifont icon_help_circle cardIcon"></i>
                </el-tooltip>
              </span>
              <MoreMenu :slicer='slicer'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        @fullScreen="fullScreen" />
            </div>

            <div class="control-section"
                 style="margin: 10px 10px;">
              <!-- <div>
          <el-button @click="mergedata">merge</el-button>
        </div> -->
              <div class="content-wrapper">
                <ejs-grid v-if="isHasData"
                          :style="{ height: gadgetHeight-60 + 'px' }"
                          :dataSource="gridDefaultSetting.dataSource"
                          :allowResizing="gridDefaultSetting.allowResizing"
                          :allowFiltering="gridDefaultSetting.allowFiltering"
                          :filterSettings="gridDefaultSetting.filterSettings"
                          :allowGrouping="gridDefaultSetting.allowGrouping"
                          :allowPaging="gridDefaultSetting.allowPaging"
                          :height="gadgetHeight - 250"
                          :toolbar="gridDefaultSetting.toolbar"
                          :allowTextWrap="gridDefaultSetting.allowTextWrap"
                          :showColumnChooser="gridDefaultSetting.showColumnChooser"
                          :allowReordering="gridDefaultSetting.allowReordering"
                          :allowSorting="gridDefaultSetting.allowSorting"
                          :load="load"
                          :dataBound="dataBound"
                          :pageSettings="gridDefaultSetting.pageSettings"
                          ref="datagrid"
                          :showColumnMenu='gridDefaultSetting.showColumnMenu'
                          :toolbarClick='toolbarClick'
                          :allowExcelExport='gridDefaultSetting.allowExcelExport'
                          :allowPdfExport='gridDefaultSetting.allowPdfExport'>
                </ejs-grid>
                <div v-else
                     class="gadget-no-data">
                  <el-image @click="query()"
                            :src="noDataImageUrl"
                            fit="fill"></el-image>
                </div>
              </div>
            </div>

          </div>
        </el-card>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import mixinViewModule from '@/mixins/simplereport-view-module'
// import model from '@/components/gadget/query-model/query-model.vue'
import linkFormat from './template/linkFormat'
import boolFormat from './template/boolFormat'
import progessFormat from './template/progessFormat'
import progessFullFormat from './template/progessfullFormat'
import DrillThroughLinkFormat from './template/DrillThroughLinkFormat'
import ticketLinkFormat from './template/ticketLinkFormat'
import timeEntryLinkFormat from './template/timeEntryLinkFormat'
import { DataTransmit } from './template/dataTransmit'
import dateFormat from './template/dateFormat'
import textFormat from './template/textFormat'

import { defaultGadgetSettingList } from '@/utils/data-json'
export default {
  mixins: [mixinGadgetViewModule, mixinViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },

  data () {
    return {
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      reportSetting: null,
      heightoffset: 60,
      headText: '',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'grid',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'grid' }).gadgetSetting
          // gadgetSetting: {
          //   headerTitle: '',
          //   headerDescription: ''
          // }
        }
      },
      LinkFormat: function () {
        return { template: linkFormat }
      },
      BoolFormat: function () {
        return { template: boolFormat }
      },
      ProgessFormat: function () {
        return { template: progessFormat }
      },
      ProgessfullFormat: function () {
        return { template: progessFullFormat }
      },
      DrillThroughLinkFormat: function () {
        return { template: DrillThroughLinkFormat }
      },
      DateFormat: function () {
        return { template: dateFormat }
      },
      TicketLinkFormat: function () {
        return { template: ticketLinkFormat }
      },
      TimeEntryLinkFormat: function () {
        return { template: timeEntryLinkFormat }
      },
      TextFormat: function () {
        return { template: textFormat }
      },
      MRtemplate: function () {
        return {
          template: Vue.component('MRtemplate', {
            template: ` <el-tooltip open-delay="1000" class="item" effect="dark" content="Message Count That User Reply To Bot" placement="top">
                          <div style="text-align:left">{{$data.data.field}}</div>
                        </el-tooltip>
                        `
          })
        }
      },
      MRDtemplate: function () {
        return {
          template: Vue.component('MRDtemplate', {
            template: ` <el-tooltip open-delay="1000" class="item" effect="dark" content="Message Read Count" placement="top">
                          <div style="text-align:left">{{$data.data.field}}</div>
                        </el-tooltip>
                        `
          })
        }
      },
      MRUtemplate: function () {
        return {
          template: Vue.component('MRUtemplate', {
            template: ` <el-tooltip open-delay="1000" class="item" effect="dark" content="Message Reading User Count" placement="top">
                          <div style="text-align:left">{{$data.data.field}}</div>
                        </el-tooltip>
                        `
          })
        }
      },
      MStemplate: function () {
        return {
          template: Vue.component('MStemplate', {
            template: ` <el-tooltip open-delay="1000" class="item" effect="dark" content="Sent Message Count" placement="top">
                          <div style="text-align:left">{{$data.data.field}}</div>
                        </el-tooltip>
                        `
          })
        }
      }

    }
  },

  created () {
    // this.query()
    Vue['_this_old_grid'] = this
    DataTransmit.$on('needData', () => {
      DataTransmit.$emit('giveData', this)
    })
    this.subscribeMessage('runReport', this.query)
    this.$store.state.isWidget = false
  },
  computed: {
    frozenColumns () {
      if (this.pageId === 'clients-detailed-Info' || this.pageId === '1335900324766535682') {
        return 1
      } else {
        return 0
      }
    }
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    }
  },
  methods: {
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.gadgetInfo.h * 20 - 15
    },
    applyGadgetSetting () {
      var groupSettings = { groupSettings: this.reportSetting.groupSettings }
      delete this.reportSetting.groupSettings
      var filterSettings = { filterSettings: this.reportSetting.filterSettings }
      delete this.reportSetting.filterSettings
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.reportSetting.columns.length; index++) {
        const element = this.reportSetting.columns[index]
        columnsList.push(element.field)
        if (this.reportSetting.columns[0] && !this.reportSetting.columns[0].width) {
          isAutofit = true
        }
        if (element.templateName && element.templateName === 'linkFormat') {
          this.reportSetting.columns[index].template = this.LinkFormat
        } else if (element.templateName && element.templateName === 'boolFormat') {
          this.reportSetting.columns[index].template = this.BoolFormat
        } else if (element.templateName && element.templateName === 'progessFormat') {
          this.reportSetting.columns[index].template = this.ProgessFormat
        } else if (element.templateName && element.templateName === 'dateFormat') {
          this.reportSetting.columns[index].template = this.DateFormat
        } else if (element.templateName && element.templateName === 'progessFullFormat') {
          this.reportSetting.columns[index].template = this.ProgessfullFormat
        } else if (element.templateName && element.templateName === 'ticketLinkFormat') {
          this.reportSetting.columns[index].template = this.TicketLinkFormat
        } else if (element.templateName && element.templateName === 'timeEntryLinkFormat') {
          this.reportSetting.columns[index].template = this.TimeEntryLinkFormat
        } else if (element.templateName && element.templateName === 'textFormat') {
          this.reportSetting.columns[index].template = this.TextFormat
        }
        if (element.foreignKeyField && element.foreignKeyField === 'MR') { // MR
          if (this.frozenColumns > 0) {
            this.reportSetting.columns[index].headerTemplate = this.MRtemplate
          }
        }
        if (element.foreignKeyField && element.foreignKeyField === 'MRD') {
          if (this.frozenColumns > 0) {
            this.reportSetting.columns[index].headerTemplate = this.MRDtemplate
          }
        }
        if (element.foreignKeyField && element.foreignKeyField === 'MRU') {
          if (this.frozenColumns > 0) {
            this.reportSetting.columns[index].headerTemplate = this.MRUtemplate
          }
        }
        if (element.foreignKeyField && element.foreignKeyField === 'MS') {
          if (this.frozenColumns > 0) {
            this.reportSetting.columns[index].headerTemplate = this.MStemplate
          }
        }

        try {
          if (element.drillThrough && element.drillThrough.status) {
            this.reportSetting.columns[index].template = this.DrillThroughLinkFormat
          }
        } catch (e) {
        }
      }
      if (isAutofit) {
        this.$refs.datagrid.autoFitColumns(columnsList)
      }
      if (this.frozenColumns > 0) {
        for (let i = 0; i < this.reportSetting.columns.length; i++) {
          const item = this.reportSetting.columns[i]
          item.autoFit = true
        }
      }
      this.grid.ej2Instances.setProperties(this.reportSetting)
      this.grid.ej2Instances.setProperties(filterSettings)
      this.grid.ej2Instances.setProperties(groupSettings)
    },
    findColumnIndex (arr) {
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index]
        if (element.field === 'Name') {
          return index
        }
      }
      return -1
    },
    mergedata () {
      this._.merge(this.reportSetting, JSON.parse(this.grid.ej2Instances.getPersistData()))
      this.applyGadgetSetting()
    },
    saveGadgetSetting () {
      var _self = this
      _self.reportSetting = JSON.parse(this.grid.ej2Instances.getPersistData())
      this._.merge(_self.reportSetting, _self.queryModelDefaultSetting.dataInfo.gadgetSetting)
      // grid table , save obj  from json obj
      let gridobj = null
      gridobj = {
        report: _self.reportSetting
      }
      const params = {
        gadgetSetting: gridobj,
        gadgetId: this.id
      }
      this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
      })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.dataInfo.settingComponent = 'gridgadgetsetting'
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          (this.$refs['datagrid']).pdfExport()
          break
        case 'Excel Export':
          (this.$refs['datagrid']).excelExport()
          break
        case 'CSV Export':
          (this.$refs['datagrid']).csvExport()
          break
      }
    },
    query (ignoreColumn) {
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.isHasData = false
      this.loading = true
      var _self = this
      var param = {
        ...this.slicer,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr()
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          if (param.current) {
            _self.gridDefaultSetting.dataSource = res.data.records
            this.pageOptions.total = res.data.total * 1
            this.pageOptions.currentPage = res.data.current * 1
          } else {
            _self.gridDefaultSetting.dataSource = res.data
          }
          this.heightoffset = 5
          _self.gadgetHeight = (_self.gadgetInfo.h * 20) - _self.heightoffset - 15
          // process config
          if (!ignoreColumn) {
            if (res.config) {
              _self.reportSetting = res.config.report || res.config
              _self.queryModelDefaultSetting.dataInfo.gadgetSetting = _self.reportSetting
              // _self.isGridInit = false
            }
          }
          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
          }
          // }
          _self.isGridInit = false
          _self.isHasData = true
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    }
  },
  destroyed () {
    delete Vue['_this_old_grid']
    DataTransmit.$off('needData')
  },
  remove () {
    this.close()
    if (this.drop.parentNode) {
      this.drop.parentNode.removeChild(this.drop)
    }
  }
}
</script>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
</style>
